"""
Pydantic数据模型定义
"""
from typing import List, Optional, Dict, Any
from pydantic import BaseModel, Field
from enum import Enum


# ==================== 通用类型 ====================
class Location(BaseModel):
    """位置坐标"""

    x: float = Field(..., description="经度")
    y: float = Field(..., description="纬度")


class TrajectoryPoint(BaseModel):
    """轨迹点"""

    x: float
    y: float
    timestamp: str


class AlertLevel(str, Enum):
    """告警级别"""

    LOW = "low"
    MEDIUM = "medium"
    HIGH = "high"


class Severity(str, Enum):
    """严重程度"""

    LOW = "low"
    MEDIUM = "medium"
    HIGH = "high"


# ==================== 模型指标 ====================
class ModelMetrics(BaseModel):
    """模型性能指标"""

    accuracy: float = Field(..., description="准确率 (0-1)")
    f1Score: float = Field(..., alias="f1", description="F1分数 (0-1)")
    precision: Optional[float] = Field(None, description="精确率 (0-1)")
    recall: Optional[float] = Field(None, description="召回率 (0-1)")
    rocAuc: Optional[float] = Field(None, description="ROC曲线下面积 (0-1)")

    class Config:
        populate_by_name = True


# ==================== 总览模块 ====================
class SystemStatus(BaseModel):
    """系统状态"""

    status: str
    uptime: str
    lastUpdate: str


class RealTimeStats(BaseModel):
    """实时统计"""

    totalPeople: int
    departure: int
    retention: int
    background: int
    activity: int
    normalCount: int
    anomalyCount: int


class ModelPerformance(BaseModel):
    """模型性能"""

    model: str
    algorithm: str
    accuracy: float
    f1: float


class Alert(BaseModel):
    """告警信息"""

    time: str
    type: str
    level: str
    message: str


class OverviewData(BaseModel):
    """总览数据"""

    systemStatus: SystemStatus
    realTimeStats: RealTimeStats
    modelsPerformance: List[ModelPerformance]
    recentAlerts: List[Alert]


# ==================== 离场/停留识别模块 ====================
class FlowClassification(BaseModel):
    """人流分类统计"""

    departure: int
    retention: int
    total: int


class TimeSeriesData(BaseModel):
    """时间序列数据"""

    times: List[str]
    departure: List[int]
    retention: List[int]


class AreaData(BaseModel):
    """区域数据"""

    area: str
    departure: int
    retention: int


class ConfidenceDistribution(BaseModel):
    """置信度分布"""

    ranges: List[str]
    counts: List[int]


class FeatureImportance(BaseModel):
    """特征重要性"""

    feature: str
    importance: float


class DepartureRetentionData(BaseModel):
    """离场/停留识别数据"""

    modelMetrics: ModelMetrics
    flowClassification: FlowClassification
    timeSeriesData: TimeSeriesData
    heatmapData: List[AreaData]
    confidenceDistribution: ConfidenceDistribution
    featureImportance: List[FeatureImportance]


# ==================== 预测请求 ====================
class PredictionRequest(BaseModel):
    """单个预测请求"""

    location: Location
    trajectory: List[TrajectoryPoint] = []
    dwellTime: int = Field(..., description="停留时间(秒)")
    features: Optional[Dict[str, Any]] = None


class BatchPredictionRequest(BaseModel):
    """批量预测请求"""

    data: List[PredictionRequest]


class PredictionResponse(BaseModel):
    """预测响应"""

    prediction: str
    confidence: float
    probability: Optional[Dict[str, float]] = None


class BatchPredictionResponse(BaseModel):
    """批量预测响应"""

    results: List[PredictionResponse]
    summary: Dict[str, int]


# ==================== 背景/活动区分模块 ====================
class BackgroundActivityClassification(BaseModel):
    """背景/活动分类统计"""

    background: int
    activity: int
    total: int


class BackgroundActivityTimeSeries(BaseModel):
    """背景/活动时间序列"""

    times: List[str]
    background: List[int]
    activity: List[int]


class ClusterData(BaseModel):
    """聚类数据"""

    clusterId: int
    type: str
    centerX: float
    centerY: float
    size: int
    density: float


class ActivityHeatmapPoint(BaseModel):
    """活动热力图点"""

    x: int
    y: int
    intensity: float
    type: str


class DecisionRule(BaseModel):
    """决策规则"""

    rule: str
    classification: str
    confidence: float


class BackgroundActivityData(BaseModel):
    """背景/活动区分数据"""

    modelMetrics: ModelMetrics
    flowClassification: BackgroundActivityClassification
    timeSeriesData: BackgroundActivityTimeSeries
    clusterData: List[ClusterData]
    featureImportance: List[FeatureImportance]
    activityHeatmap: List[ActivityHeatmapPoint]
    decisionRules: List[DecisionRule]


# ==================== 异常检测模块 ====================
class MicroMetrics(BaseModel):
    """微观指标"""

    precision: float
    recall: float
    featureDimensions: int


class MesoMetrics(BaseModel):
    """中观指标"""

    precision: float
    recall: float
    featureDimensions: int


class AnomalyModelMetrics(BaseModel):
    """异常检测模型指标"""

    micro: MicroMetrics
    meso: MesoMetrics


class AnomalyStats(BaseModel):
    """异常统计"""

    normal: int
    microAnomaly: int
    mesoAnomaly: int
    total: int


class AnomalyTimeSeries(BaseModel):
    """异常时间序列"""

    times: List[str]
    normal: List[int]
    anomaly: List[int]


class MicroAnomaly(BaseModel):
    """微观异常"""

    id: str
    timestamp: str
    type: str
    location: Location
    confidence: float
    severity: str


class MesoAnomaly(BaseModel):
    """中观异常"""

    id: str
    timestamp: str
    station: str
    type: str
    affectedCount: int
    confidence: float
    severity: str


class AnomalyType(BaseModel):
    """异常类型"""

    type: str
    count: int
    severity: str


class AnomalyConfidenceDistribution(BaseModel):
    """异常置信度分布"""

    ranges: List[str]
    micro: List[int]
    meso: List[int]


class AnomalyDetectionData(BaseModel):
    """异常检测数据"""

    modelMetrics: AnomalyModelMetrics
    anomalyStats: AnomalyStats
    timeSeriesData: AnomalyTimeSeries
    microAnomalies: List[MicroAnomaly]
    mesoAnomalies: List[MesoAnomaly]
    anomalyTypes: List[AnomalyType]
    microFeatureImportance: List[FeatureImportance]
    mesoFeatureImportance: List[FeatureImportance]
    confidenceDistribution: AnomalyConfidenceDistribution


class AnomalyHandleResponse(BaseModel):
    """异常处理响应"""

    anomalyId: str
    handled: bool
    handledAt: str
